//
//  RBGesturePwdView.m
//  4-24-1 手势密码demo
//  Created by 华杨科技 on 2017/4/24.
//  Copyright © 2017年 饶波. All rights reserved.
//

#import "RBGesturePwdView.h"
#import "RBPwdHeader.h"
#import "RBPwdItem.h"
#import "UIColor+KLHex.h"
#import "RBPwdIcon.h"

#import "KeychainData.h"

#define KscreenHeight [UIScreen mainScreen].bounds.size.height
#define KscreenWidth [UIScreen mainScreen].bounds.size.width
#define ITEMTAG 4444

@interface RBGesturePwdView()
@property (nonatomic, strong) RBPwdIcon *iconView; // 上部（icon + name + reminder提示文字）

@property (nonatomic, strong) NSMutableArray *btnArray; // 盛放密码的数组
@property (nonatomic, assign) CGPoint movePoint; // 移动的点

@property (nonatomic, strong) UIButton *forgetPwdBtn; // 底部忘记手势密码button

@end

@implementation RBGesturePwdView
#pragma mark - lazy
- (RBPwdIcon *)iconView {
    if (!_iconView) {
        _iconView = [[RBPwdIcon alloc] initWithFrame:CGRectMake(0, 50, KscreenWidth, ICONVIEW_H)];
        _iconView.backgroundColor = [UIColor grayColor]; // 先搞个颜色
    }
    return _iconView;
}

- (NSMutableArray *)btnArray {
    if (!_btnArray) {
        _btnArray = [NSMutableArray array];
    }
    return _btnArray;
}

#pragma mark 一:布局子视图
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initViews];
    }
    return self;
}

- (void)initViews {
//    self.backgroundColor = BACKGROUNDCOLOR;
    self.backgroundColor = [UIColor kl_convertToRGBColorWithHexValue:0x3c3c3c];
    
    // 上面：icon 、提示文字
    [self addSubview:self.iconView];
    
    // 中间：九宫格密码
    [self createPoint_nine];
    
    // 底部：添加底部忘记密码button
    [self createForgetButton];
}

// 9宫格布局
- (void)createPoint_nine {
    for (int i = 0; i < 9; i++) {
        
        int row = i/3;
        int column = i % 3;
        /** 
         row  column
         0       0
         0       1
         0       2
         1       0
         1       1
         1       2
         2       0
         2       1
         2       2
         */
        
        CGFloat spaceFloat = (KscreenWidth - 3*ITEMWH)/ 4 ; // 间距
        CGFloat pointX = spaceFloat * (column +1) + ITEMWH*column;
        CGFloat pointY = ITEM_TOTAL_POSITION + spaceFloat * row + ITEMWH *row;
        
        RBPwdItem *item = [[RBPwdItem alloc] initWithFrame:CGRectMake(pointX, pointY, ITEMWH, ITEMWH)];
        item.userInteractionEnabled = YES;
        item.isSelect = NO;
        item.tag = ITEMTAG + i;
        
        
        [self addSubview:item];
    }
}

- (void)createForgetButton {
    self.forgetPwdBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    CGFloat btn_x = 50;
    CGFloat space = (KscreenWidth - 3*ITEMWH)/ 2;
    // 整个item的顶点位置 + space + 20
    CGFloat btn_y = ITEM_TOTAL_POSITION + space + 3*ITEMWH + 30;
    CGFloat btn_w = KscreenWidth - 100;
    CGFloat btn_h = 30;
    
    CGRect frame = CGRectMake(btn_x, btn_y, btn_w, btn_h);
    self.forgetPwdBtn.frame = frame;
    
    [self.forgetPwdBtn setTitle:@"忘记手势密码" forState:(UIControlStateNormal)];
//    [self.forgetPwdBtn setTitleColor:[UIColor blueColor] forState:(UIControlStateNormal)];
    
    [self addSubview:self.forgetPwdBtn];
}

#pragma mark 二:触摸事件
/**
 touch begin
 */
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    
    // 获取坐标点
    CGPoint point =  [self touchLocation:touches];
    
    // 判断是否包含该点
    [self isContainItem:point];
}

/**
 touch moved
 */
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesMoved:touches withEvent:event];
    
    CGPoint point = [self touchLocation:touches];
    
    [self isContainItem:point];
    
    // 设置箭头方向
    [self touchMove_triangleAction];
    
    [self setNeedsDisplay];
}

/**
 touch ended
 */
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [super touchesEnded:touches withEvent:event];
    
    [self touchEndedRemoveAllStyle];
    
    [self setNeedsDisplay];
    
}

#pragma mark 三:触摸事件代码封装方法
/**
 touch begin move
 */
// 1.获取触摸点
- (CGPoint)touchLocation:(NSSet *)touches {
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];  // 在view上的点
    
    _movePoint = point;
    
    return point;
}

// 2.是否包含密码点：
- (void)isContainItem:(CGPoint)point {
    for (RBPwdItem *pwdItem in self.subviews) {
        if ([pwdItem isKindOfClass:[RBPwdItem class]]) {
            
            // Return true if `point' is contained in `rect', false otherwise
            BOOL isContain = CGRectContainsPoint(pwdItem.frame, point);
            
            if (isContain && (pwdItem.isSelect == NO)) {
                [self.btnArray addObject:pwdItem]; // 保存密码
                pwdItem.isSelect = YES;
                pwdItem.styleModel = selectStyle;
            }
        }
    }
}

// 3.修改小箭头的方向
- (void)touchMove_triangleAction{
    NSString *resultStr = [self getResultPwd];
    if (resultStr&&resultStr.length>0   )
    {
        NSArray *resultArr = [resultStr componentsSeparatedByString:@"A"];
        if ([resultArr isKindOfClass:[NSArray class]]  &&  resultArr.count>2 )
        {
            NSString *lastTag    = resultArr[resultArr.count-1];
            NSString *lastTwoTag = resultArr[resultArr.count-2];
            
            CGPoint lastP ;
            CGPoint lastTwoP;
            RBPwdItem *lastItem;
            
            for (RBPwdItem *item  in self.btnArray)
            {
                if (item.tag-ITEMTAG == lastTag.intValue)
                {
                    lastP = item.center;
                }
                if (item.tag-ITEMTAG == lastTwoTag.intValue)
                {
                    lastTwoP = item.center;
                    lastItem = item;
                }
                
                CGFloat x1 = lastTwoP.x;
                CGFloat y1 = lastTwoP.y;
                CGFloat x2 = lastP.x;
                CGFloat y2 = lastP.y;
                
                [lastItem judgeTriangleDirectionWithx1:x1 y1:y1 x2:x2 y2:y2 isHidden:NO];
                
            }
        }
    }
}


/**触摸结束*/
// 触摸结束:移除所有样式
- (void)touchEndedRemoveAllStyle {
    for (RBPwdItem *item in self.btnArray) {
        [item judgeTriangleDirectionWithx1:0 y1:0 x2:0 y2:0 isHidden:NO];
    }
    
    if (![self lessFourPoint])
    {
        [self setPwdMethod:[self getResultPwd]];
        
        NSString *pwd =  [self resultPwdWithAString:[self getResultPwd]];
        NSLog(@"您的密码是:%@",pwd);
    }
    
    
    [self.btnArray removeAllObjects];
    
    // 选中样式
    for (RBPwdItem *item in self.subviews) {
        if ([item isKindOfClass:[RBPwdItem class]]) {
            item.isSelect = NO;
            item.styleModel = normalStyle;
            
            [item judgeTriangleDirectionWithx1:0 y1:0 x2:0 y2:0 isHidden:YES];
        }
    }
}

// 少于4个点
- (BOOL)lessFourPoint {
    if (self.btnArray.count <= 3) {
        self.iconView.reminderLB.textColor = WRONGCOLOR;
        self.iconView.reminderLB.text = PSW_WRONG_NUMSTRING;
        [self shake:self.iconView.reminderLB]; // 抖一抖
        return YES;
    }else{
        return NO;
    }
}


// 1.将密码数据转为字符串
- (NSString *)getResultPwd {
    NSMutableString *resultStr = [NSMutableString string];
    for (RBPwdItem *item in self.btnArray) {
        if ([item isKindOfClass:[RBPwdItem class]]) {
            
            [resultStr appendString:@"A"]; // 方便后边切割
            [resultStr appendString:[NSString stringWithFormat:@"%ld",(long)(item.tag - ITEMTAG)]];
        }
    }
//    NSLog(@"密码: %@",resultStr);
    return resultStr;
}

#pragma mark 四:label 的属性设置 抖一抖
- (void)shake:(UIView*)myView{
    int offset = 8;
    
    CALayer *labelLayer = [myView layer];
    CGPoint labelPosition = [labelLayer position];
    // y 轴不变，让他左右晃
    CGPoint y = CGPointMake(labelPosition.x-offset, labelPosition.y);
    CGPoint x = CGPointMake(labelPosition.x+offset, labelPosition.y);
    
    // 基础动画
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    // 定时函数:  http://www.jianshu.com/p/a4d774315613
    CAMediaTimingFunction *timingFuc = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; // 渐进渐出效果
    
    [animation setTimingFunction:timingFuc];
    [animation setFromValue:[NSValue valueWithCGPoint:x]];
    [animation setToValue:[NSValue valueWithCGPoint:y]];
    [animation setAutoreverses:YES];
    [animation setDuration:0.08];
    [animation setRepeatCount:2];
    [labelLayer addAnimation:animation forKey:nil];
}

#pragma mark 五:设置、修改、登录业务逻辑代码
- (void)setPwdMethod:(NSString *)resultStr {

    //没有任何记录，第一次登录
    BOOL isSaveBool = [KeychainData isFirstInput:resultStr];
    
    //默认为蓝色
    UIColor *color = SELECTCOLOR;
    if (isSaveBool) {
        //第一次输入之后，显示的文字
        self.iconView.reminderLB.text = RESETPSWSTRING;
        self.iconView.reminderLB.textColor = [UIColor whiteColor];
    }else {
        //验证密码
        color = [self validatePwdJudgeAction:color str:resultStr];
    }
}

/**
 *  验证，登录
 */
- (UIColor *)validatePwdJudgeAction:(UIColor *)color str:(NSString *)resultStr
{
    BOOL isValidate = [KeychainData isSecondInputRight:resultStr];
        if (isValidate) {
            //如果验证成功
            self.iconView.reminderLB.text = VALIDATE_PSWSTRING_SUCCESS;
            self.iconView.reminderLB.textColor = [UIColor whiteColor];
            [self performSelector:@selector(blockAction:) withObject:resultStr afterDelay:.8];
            
        } else {
            //失败
            self.iconView.reminderLB.text = PSWFAILTSTRING;
            self.iconView.reminderLB.textColor = LABELWRONGCOLOR;
            [self shake:self.iconView.reminderLB];
            color = LABELWRONGCOLOR;
        }
    return color;
}

/**
 *   成功的block回调
 */
- (void)blockAction:(NSString *)resultStr
{
    if (self.block)
    {
        _gestureModel = NoneModel;
        self.block([resultStr stringByReplacingOccurrencesOfString:@"A" withString:@"__"]);
    }
}


#pragma mark 六: drawRect
- (void)drawRect:(CGRect)rect {
    UIBezierPath *path = [UIBezierPath bezierPath];
    
    for (int i=0; i<self.btnArray.count; i++)
    {
        RBPwdItem *item = (RBPwdItem *)self.btnArray[i];
        if (i==0)
        {
            [path moveToPoint:item.center];
        }
        else
        {
            [path addLineToPoint:item.center];
        }
    }
    
    if (_movePoint.x!=0 && _movePoint.y!=0 && NSStringFromCGPoint(_movePoint))
    {
        [path addLineToPoint:_movePoint];
    }
    [path setLineCapStyle:kCGLineCapRound];
    [path setLineJoinStyle:kCGLineJoinRound];
    [path setLineWidth:1.0f];
    [SELECTCOLOR setStroke];
    [path stroke];
}

#pragma mark 七:只保留数字密码
// 为了处理方便，把密码拼接上了 'A',这里 ‘A’ 去掉，只保留数字
- (NSString *)resultPwdWithAString:(NSString *)AString {
    AString = [AString stringByReplacingOccurrencesOfString:@"A" withString:@""];
    return AString;
}

#pragma mark - 公共方法
// 通过block把 button 带出去
- (void)forgetGesturePwdBlock:(void (^)(UIButton *))forgetBtnBlock{
    
    forgetBtnBlock(self.forgetPwdBtn);
    
}

/** 给iconView 赋值 */
- (void)setIconWithImgStr:(NSString *)imgStr name:(NSString *)name reminder:(NSString *)reminder{
    self.iconView.iconIV.image = [UIImage imageNamed:imgStr];
    self.iconView.nameLB.text = name;
    self.iconView.reminderLB.text = reminder;
}

@end
